package com.nightsoul.dubbo.action;

import org.junit.Test;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import com.nightsoul.dubbo.provider.service.DemoService;
import com.nightsoul.dubbo.provider.service.impl.DemoServiceImpl;

public class APIConfig {
	
	@Test
	public void runProvider() throws Exception {
		DemoService demoService = new DemoServiceImpl();
		
		//当前应用配置
		ApplicationConfig application = new ApplicationConfig();
		application.setName("test_app");
		
		//连接注册中心配置
		RegistryConfig registry = new RegistryConfig();
		registry.setAddress("multicast://224.5.6.109:1234?unicast=false");
		registry.setUsername("zhangsan");
		registry.setPassword("xtayfjpk");
		
		//服务提供者协议配置
		ProtocolConfig protocol = new ProtocolConfig();
		protocol.setName("dubbo");
		protocol.setPort(12345);
		protocol.setThreads(200);
		
		//注意：ServiceConfig为重对象，内部封闭了与注册中心的连接，以及开启服务商品
		//服务提供者暴露服务配置
		ServiceConfig<DemoService> service = new ServiceConfig<>();
		service.setApplication(application);
		service.setRegistry(registry);
		service.setProtocol(protocol);
		service.setInterface(DemoService.class);
		service.setRef(demoService);
		service.setVersion("1.0.0");
		
		//暴露及注册服务
		service.export();
		
		System.in.read();
	}
	
	@Test
	public void runConsumer() throws Exception {
		//当前应用配置
		ApplicationConfig application = new ApplicationConfig();
		application.setName("test_app_consumer");
		
		//连接注册中心配置
		RegistryConfig registry = new RegistryConfig();
		registry.setAddress("multicast://224.5.6.109:1234");
		registry.setUsername("zhangsan");
		registry.setPassword("xtayfjpk");
		
		//注意：ReferenceConfig为重对象，内部封装与注册中心连接，以及与服务提供方的连接
		
		//引用远程服务
		ReferenceConfig<DemoService> reference = new ReferenceConfig<>();
		reference.setApplication(application);
		reference.setRegistry(registry);
		reference.setInterface(DemoService.class);
		reference.setVersion("1.0.0");
		
		//和本地bean一样使用DemoService
		DemoService demoService = reference.get();
		System.out.println(demoService.sayHello("张三"));
		
	}
}
